var $ModalChange = $('#exampleModalChange');
var $treeTable = $('#tb_departments');
$treeTable.bootstrapTable({

    classes: 'table table-bordered table-hover table-striped',
    url: '/admin/admin/datalist',
    method: 'get',
    dataType: 'json', // 因为本示例中是跨域的调用,所以涉及到ajax都采用jsonp,
    uniqueId: 'id',
    idField: 'id', // 每行的唯一标识字段
    toolbar: '#toolbar2', // 工具按钮容器
    //clickToSelect: true,     // 是否启用点击选中行
    showColumns: true, // 是否显示所有的列
    showToggle: true, // 是否显示详细视图和列表视图的切换按钮(clickToSelect同时设置为true时点击会报错)
    pagination: true, // 是否显示分页
    sortOrder: "asc", // 排序方式

    columns: [
        {
            field: 'check',
            checkbox: true
        },
        {
            field: 'id',
            title: '用户ID'
        },
        {
            field: 'username',
            title: '账号'
        },
        {
            field: 'nickname',
            title: '昵称'
        },
        {
            field: 'roleName',
            title: '所属角色',
            formatter: function(value, row, index) {
                if(row.is_admin == 1){
                    return '<a href="#!" class="badge badge-primary">超级管理员</a>'
                }else{
                    return row.roles.map(function (item) {
                        return '<a href="#!" class="badge badge-success">'+item.title+'</a>';
                    }).join('&nbsp;&nbsp;');
                }
            },
        },
        {
            field: 'last_login_time',
            title: '上次登录时间'
        },
        {
            field: 'login_time',
            title: '登录时间'
        },
        {
            field: 'create_time',
            title: '创建时间'
        },
        {
            field: 'status',
            title: '昵称',
            formatter: function(value, row, index) {
                if (value == 0) {
                    is_checked = '';
                } else if (value == 1) {
                    is_checked = 'checked="checked"';
                }
                result = '<div class="custom-control custom-switch"><input type="checkbox" class="custom-control-input" id="customSwitch' + row.id + '" ' + is_checked + '><label class="custom-control-label" for="customSwitch' + row.id + '" onClick="updateStatus(' + row.id + ', ' + value + ')"></label></div>';

                return result;
            },
        },
        {
            field: 'operate',
            title: '操作',
            align: 'center',
            events: {
                'click .role-add': function(e, value, row, index) {
                    //add(row.id);
                },
                'click .role-delete': function(e, value, row, index) {
                    del(row.id);
                },
                'click .role-edit': function(e, value, row, index) {
                    //update(row.id);
                }
            },
            formatter: operateFormatter
        }
    ],

    responseHandler: function(res) {
        return {
            //"total": res.DATA.totalRecordCount,//总页数
            "rows": res.data.data   //数据
        };
    },

    treeShowField: 'name',
    parentIdField: 'pid',
    search:false,  //是否启用搜索框
    searchOnEnterKey:false,  //按回车触发搜索方法
    showRefresh: true,  //是否显示刷新按钮

});

// 操作按钮
function operateFormatter(value, row, index) {
    return [
        '<a type="button" class="role-edit btn btn-xs btn-default m-r-5" title="修改" data-toggle="modal" data-target="#exampleModalChange" data-whatever="'+row.id+'" data-toggle="tooltip"><i class="mdi mdi-pencil"></i></a>',
        '<a type="button" class="role-delete btn btn-xs btn-default" title="删除" data-toggle="tooltip"><i class="mdi mdi-delete"></i></a>'
    ].join('');
}

/**
 * 选中父项时，同时选中子项
 * @param datas 所有的数据
 * @param row 当前数据
 * @param id id 字段名
 * @param pid 父id字段名
 */
function selectChilds(datas, row, id, pid, checked) {
    for (var i in datas) {
        if (datas[i][pid] == row[id]) {
            datas[i].check = checked;
            selectChilds(datas, datas[i], id, pid, checked);
        };
    }
}

function selectParentChecked(datas, row, id, pid) {
    for (var i in datas) {
        if (datas[i][id] == row[pid]) {
            datas[i].check = true;
            selectParentChecked(datas, datas[i], id, pid);
        };
    }
}

$('#exampleModalChange').on('show.bs.modal', function (event) {
    $('.selectpicker').selectpicker();
    var button = $(event.relatedTarget);
    var recipient = button.data('whatever');
    var modal = $(this);
    if(recipient != 0){
        var data = {
            id:recipient
        }
        $.ajax({
            url: '/admin/admin/index',
            data:data,
            type: 'POST',
            dataType: 'json'
        }).done(function(response) {
            modal.find('.modal-title').text('编辑' + response.data.username);
            modal.find('.modal-body [name=id]').val(recipient);
            modal.find('.modal-body [name=username]').val(response.data.username);
            modal.find('.modal-body [name=nickname]').val(response.data.nickname);
            var s1 = response.data.roles;
            var s = eval(s1);
            var a = [];
            for(var i=0;i<s.length;i++){
                console.log(s[i].group.id)
                a.push(s[i].group.id)
            }
            $('.selectpicker').selectpicker('val', a);
        }).fail(function() {
            console.error('数据错误');
        });
    }else{
        modal.find('.modal-title').text('新增角色');
        modal.find('.modal-body [name=id]').val('0');
        modal.find('.modal-body [name=username]').val('');
        modal.find('.modal-body [name=nickname]').val('');
        modal.find('.modal-body [name=newpassword]').val('');
        modal.find('.modal-body [name=repassword]').val('');
        $('.selectpicker').selectpicker('deselectAll');
    }
})


function post_submit() {
    $.ajax({
        //几个参数需要注意一下
        type: "POST",//方法类型
        dataType: "json",//预期服务器返回的数据类型
        url: "/admin/admin/post_submit" ,//url
        data: $('#form1').serialize(),
        success: function (res) {
            console.log(res);//打印服务端返回的数据(调试用)
            if (res.code === 0) {
                $.alert({
                    title: '成功',
                    icon: 'mdi mdi-alert',
                    type: 'blue',
                    content: res.msg,
                    buttons: {
                        okay: {
                            text: '确认',
                            btnClass: 'btn-blue',
                            action: function() {
                                $ModalChange.modal('hide');
                                $treeTable.bootstrapTable('refresh');
                            }
                        }
                    }
                });
            }else {
                $.alert({
                    title: '错误',
                    icon: 'mdi mdi-alert',
                    type: 'red',
                    content: res.msg,
                    buttons: {
                        okay: {
                            text: '确认',
                            btnClass: 'btn-blue',
                            action: function() {
                                //$('[alt="captcha"]').click();
                            }
                        }
                    }
                });
            };
        },
        error : function() {
            $.alert({
                title: '警告',
                content: '请检查返回是否正常！',
                icon: 'mdi mdi-access-point-network-off',
                animation: 'scale',
                closeAnimation: 'scale',
                buttons: {
                    okay: {
                        text: '确认',
                        btnClass: 'btn-blue'
                    }
                }
            });
        }
    });
}
function add(id) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,                                // 指定为iframe模式，当值为false的时候，为智能模式，自动判断（内网用ajax，外网用iframe）。缺省为false。
        title : '添加节点',                     // 标题（可选），没有则显示网址
        url : '/admin/admin/authlist?id=' + id                    // 链接（必须），如为外链，强制为info页
    }, true);
}
function del(id) {
    $.confirm({
        title: '提示',
        content: '您确定要删除此角色？',
        icon: 'mdi mdi-alert',
        animation: 'scale',
        closeAnimation: 'zoom',
        buttons: {
            confirm: {
                text: '是的',
                btnClass: 'btn-orange',
                action: function() {
                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "/admin/admin/del" ,//url
                        data: {id: id},
                        success: function (res) {
                            console.log(res);//打印服务端返回的数据(调试用)
                            if (res.code === 0) {
                                $.alert({
                                    title: '成功',
                                    icon: 'mdi mdi-alert',
                                    type: 'blue',
                                    content: res.msg,
                                    buttons: {
                                        okay: {
                                            text: '确认',
                                            btnClass: 'btn-blue',
                                            action: function() {
                                                $treeTable.bootstrapTable('refresh');
                                            }
                                        }
                                    }
                                });
                            }else {
                                $.alert({
                                    title: '错误',
                                    icon: 'mdi mdi-alert',
                                    type: 'red',
                                    content: res.msg,
                                    buttons: {
                                        okay: {
                                            text: '确认',
                                            btnClass: 'btn-blue',
                                            action: function() {
                                                //$('[alt="captcha"]').click();
                                            }
                                        }
                                    }
                                });
                            };
                        },
                        error : function() {
                            $.alert({
                                title: '警告',
                                content: '请检查返回是否正常！',
                                icon: 'mdi mdi-access-point-network-off',
                                animation: 'scale',
                                closeAnimation: 'scale',
                                buttons: {
                                    okay: {
                                        text: '确认',
                                        btnClass: 'btn-blue'
                                    }
                                }
                            });
                        }
                    });
                }
            },
            '取消': function() {

            }
        }
    });

}

function test() {
    var selRows = $treeTable.bootstrapTable("getSelections");
    if (selRows.length == 0) {
        alert("请至少选择一行");
        return;
    }
    console.log(selRows);

    var postData = "";
    $.each(selRows, function(i) {
        postData += this.id;
        if (i < selRows.length - 1) {
            postData += ",";
        }
    });
    $.confirm({
        title: '提示',
        content: '您确定要删除角色？',
        icon: 'mdi mdi-alert',
        animation: 'scale',
        closeAnimation: 'zoom',
        buttons: {
            confirm: {
                text: '是的',
                btnClass: 'btn-orange',
                action: function() {
                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "/admin/admin/del" ,//url
                        data: {id:'',ids: postData},
                        success: function (res) {
                            console.log(res);//打印服务端返回的数据(调试用)
                            if (res.code === 0) {
                                $.alert({
                                    title: '成功',
                                    icon: 'mdi mdi-alert',
                                    type: 'blue',
                                    content: res.msg,
                                    buttons: {
                                        okay: {
                                            text: '确认',
                                            btnClass: 'btn-blue',
                                            action: function() {
                                                $treeTable.bootstrapTable('refresh');
                                            }
                                        }
                                    }
                                });
                            }else {
                                $.alert({
                                    title: '错误',
                                    icon: 'mdi mdi-alert',
                                    type: 'red',
                                    content: res.msg,
                                    buttons: {
                                        okay: {
                                            text: '确认',
                                            btnClass: 'btn-blue',
                                            action: function() {
                                                //$('[alt="captcha"]').click();
                                            }
                                        }
                                    }
                                });
                            };
                        },
                        error : function() {
                            $.alert({
                                title: '警告',
                                content: '请检查返回是否正常！',
                                icon: 'mdi mdi-access-point-network-off',
                                animation: 'scale',
                                closeAnimation: 'scale',
                                buttons: {
                                    okay: {
                                        text: '确认',
                                        btnClass: 'btn-blue'
                                    }
                                }
                            });
                        }
                    });
                }
            },
            '取消': function() {

            }
        }
    });
}